import Layout from "@/layout/Layout.vue";
import { createRouter, createWebHistory } from "vue-router";
import nprogress from "@/utils/nprogress.js";
import { usePermissionStore } from "@/stores/permission.js";

const constantRoutes = [
  { path: "/login", component: () => import("@/Login.vue") },
  {
    path: "/chat/:applicationId",
    name: "AiChat",
    component: () => import("@/views/ai/AiAgentChat.vue"),
    props: (route) => {
      return {
        applicationId: route.params.applicationId,
        sessionId: route.query.sessionId ? route.query.sessionId : -3,
      };
    },
    meta: { title: "AI Chat" },
  },
  {
    path: "",
    name: "Layout",
    component: Layout,
    redirect: "/dashboard",
    children: [
      {
        path: "/dashboard",
        name: "Dashboard",
        component: () => import("@/views/dashboard/index.vue"),
        meta: { title: "工作台" },
      },
      {
        path: "/sysMenu",
        name: "SysMenu",
        component: () => import("@/views/system/menu/index.vue"),
        meta: { title: "菜单管理" },
      },
    ],
  },
];

const routes = [...constantRoutes];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach(() => {
  nprogress.start(); // 路由前置守卫,引入进度条
});

router.afterEach(() => {
  nprogress.close(); // 路由后置守卫，关闭进度条
});

export default router;

export async function refreshAsyncRoutes() {
  const permissionStore = usePermissionStore();
  const modules = import.meta.glob("../views/**/*.vue");

  // 清除之前添加的异步路由
  router.getRoutes().forEach((route) => {
    if (route.meta && route.meta.async) {
      router.removeRoute(route.name);
    }
  });
  // 重新获取异步路由,并添加
  await permissionStore.fetchAsyncRoutes();
  // 动态添加路由,先初始化路由
  permissionStore.asyncRoutes.forEach((route) => {
    // console.log(route);
    const importComponent = modules[`../views/${route.component}.vue`];
    // console.log(importComponent);
    router.addRoute("Layout", {
      ...route,
      component: importComponent,
      props: true,
    });
  });
}
